<template>
  <pageHeader title="创建生产计划" :breadCrumb="['生产管理', '生产工单', '创建生产计划']" :show-back="true">
    <template #footer>
      <a-button @click="router.back()">取消</a-button>
      <a-button type="primary" @click="handleOk">保存</a-button>
    </template>
    <a-spin :loading="loading" class="cantainer">
      <!-- <div class="tab">生产工单信息</div> -->
      <TitleBox title="生产工单信息"></TitleBox>
      <div class="orderBox">
        <a-row :gutter="15">
          <!-- 循环输出表单信息 -->
          <a-col :span="8" v-for="(header, index) in WorkOrderHerders.herders" :key="index">
            <a-form-item show-colon :label="header.name">
              <template v-if="!!header.code">
                {{ orderData[header.code] }}
              </template>
              <template v-if="header.name === '紧急等级'">
                <a-typography-text type="primary" v-if="orderData.emergencyLevel === 1">
                  一般
                </a-typography-text>
                <a-typography-text bold v-if="orderData.emergencyLevel === 2">
                  紧急
                </a-typography-text>
                <a-typography-text type="warning" v-if="orderData.emergencyLevel === 3">
                  加急
                </a-typography-text>
                <a-typography-text type="danger" v-if="orderData.emergencyLevel === 4">
                  特急
                </a-typography-text>
              </template>
              <template v-if="header.name === '物料属性'">
                {{
                  orderData.materialAttribute === 1
                    ? '自制'
                    : orderData.materialAttribute === 2
                    ? '委外'
                    : orderData.materialAttribute === 3
                    ? '虚拟'
                    : '采购'
                }}
              </template>
              <template v-if="header.name === '工艺路线'">
                {{ orderData.processRouteName || '未配置工艺路线' }}
              </template>
              <template v-if="header.name === '开始时间'">
                {{
                  orderData.startDate &&
                  dayjs(orderData.startDate).format('YYYY年MM月DD日')
                }}
              </template>
              <template v-if="header.name === '结束时间'">
                {{
                  orderData.endDate &&
                  dayjs(orderData.endDate).format('YYYY年MM月DD日')
                }}
              </template>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <!-- <div class="tab">生产计划信息</div> -->
      <TitleBox title="生产计划信息"></TitleBox>
      <a-form :model="formData" ref="refForm" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="8">
            <a-form-item label="生产计划编号">
              <a-input placeholder="无需输入，系统自动生成..." disabled v-model="formData.code" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划类型" field="type" :rules="getRules('计划结束时间')">
              <a-select placeholder="计划类型" v-model="formData.type" @change="
                  () => {
                    resettingDateListForm();
                  }
                ">
                <a-option :value="1">周计划</a-option>
                <a-option :value="2">月计划</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <!-- 判断是月计划/周计划 -->
            <a-form-item :label="formData.type == 1 ? '选择周' : '选择月'" v-if="!!formData.type" field="startDate" :rules="getRules(formData.type == 1 ? '选择周' : '选择月')">
              <a-month-picker v-model="formData.startDate" value-format="Date" @change="
                  (val) => {
                    refCalendar.changeShowMonth(val);
                    resettingDateListForm();
                  }
                " v-if="formData.type == 2" />
              <a-week-picker v-model="formData.startDate" @change="
                  (val) => {
                    refCalendar.changeShowMonth(val);
                    resettingDateListForm();
                  }
                " value-format="Date" :day-start-of-week="1" v-else />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="capacity" label="日标准产能:" :rules="getRules('日标准产能')">
              <a-input-number :min="1" :max="orderData.produceNumber" v-model="formData.capacity" placeholder="输入日标准产能" />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="formData.type === 2">
            <a-form-item label="标准月计划数:">
              {{ getTotal() }}
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 时间组件 -->
      <Calendar ref="refCalendar">
        <template #day="{ millisecond, dateJs }">
          <a-input-number :min="1" :max="orderData.produceNumber" :disabled="isDisabled(dateJs)" v-model="dateListForm[millisecond]" :placeholder="!isDisabled(dateJs) ? '输入排程数量' : ''" />
        </template>
      </Calendar>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, computed } from 'vue';
import { AddProducePlan } from '@/api/produce-management/OrderPlanning/index';
import { TPlanProduction } from '@/api/produce-management/OrderPlanning/type';
import { WorkOrderHerders } from '@/utils/tableHerders'; //表头信息
import { useRoute, useRouter } from 'vue-router'; //路由
import dayjs from 'dayjs'; //时间
import { Message } from '@arco-design/web-vue'; //全局提示

let route = useRoute();
let router = useRouter();
let loading = ref(false);
let refCalendar = ref();
let orderData = reactive<any>({});
let dateListForm = reactive<any>({});
let resettingDateListForm = () => {
  for (const key in dateListForm) {
    delete dateListForm[key];
  }
};
let formData = reactive<TPlanProduction>({
  type: 2,
  startDate: new Date(),
});
let refForm = ref();
// 日历
let regionList = computed(() => {
  let { startDate, type } = formData;
  if (!startDate || !type) return false;
  let nowDate = dayjs();
  let startDateJs;
  let endDateJs;
  if (type === 2) {
    startDateJs = dayjs(startDate).startOf('M');
    if (startDateJs.isSame(nowDate, 'month')) startDateJs = nowDate;
    endDateJs = startDateJs.endOf('M').startOf('D');
  } else {
    startDateJs = dayjs(startDate).startOf('w').add(1, 'day');
    endDateJs = startDateJs.endOf('w').add(1, 'day').startOf('D');
    if (nowDate.isAfter(startDateJs) && nowDate.isBefore(endDateJs)) {
      startDateJs = nowDate;
    }
  }
  if (endDateJs.isBefore(nowDate)) return false;
  return [startDateJs.subtract(1, 'day'), endDateJs.add(1, 'day')];
});
// 判断日期
let isDisabled = (dateJs: any) => {
  if (!regionList.value) return true;
  let [start, end] = regionList.value;
  if (dateJs.isAfter(start)) {
    return !dateJs.isBefore(end);
  }
  return true;
};
let handleOk = async () => {
  if (await refForm.value.validate()) return;
  let list = [];

  for (const key in dateListForm) {
    let num = dateListForm[key];
    if (num)
      list.push({
        date: dayjs(Number(key)).toJSON(),
        number: num,
      });
  }
  let totalNum = list.reduce(
    (num, { number }) => (number ? num + number : num),
    0
  );
  if (totalNum > orderData.produceNumber) {
    //
    return Message.error('生成计划数量大于工单数量');
  }
  await AddProducePlan({
    ...formData,
    startDate: dayjs(formData.startDate).toJSON(),
    data: list,
    totalNum: list.reduce(
      (num, { number }) => (number ? num + number : num),
      0
    ),
  });

  router.back();
};

onMounted(async () => {
  let order;
  try {
    order = JSON.parse(localStorage.getItem('OrderDataForm') + '');
  } catch (err) {
    //
  }
  if (order) {
    Object.assign(orderData, order);
    formData.workOrderId = order.id;
    formData.produceOrderId = order.produceOrderId;
    formData.productId = order.materialId;
    formData.emergencyLevel = order.emergencyLevel;
  }
});

let getTotal = () => {
  let num = 0;
  for (const key in dateListForm) {
    num += Number(dateListForm[key]);
  }
  return num;
};
let getRules = (name?: string) => {
  return [{ required: true, message: (name || '') + '不能为空' }];
};
</script>

<style scoped lang="less">
.cantainer {
  padding: 20px;
  width: 100%;
}
.form {
  padding-left: 100px;
  padding-right: 100px;
}
.tab {
  border-left: 4px rgb(var(--arcoblue-6)) solid;
  padding-left: 20px;
  margin-bottom: 30px;
  font-size: 20px;
}
.orderBox {
  padding-left: 70px;
}

.foot {
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px solid #e4e4e4;
  display: flex;
  justify-content: end;
}
</style>
